package com.itheima.service.impl;

import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class CategoryServiceImpl implements CategoryService {

    private final CategoryMapper categoryMapper;

    @Override
    public List<Category> list() {
        //查询所有分类
        List<Category> list = categoryMapper.list();

        // 找到所有顶级分类
        List<Category> parents = list.stream().filter(c -> c.getParentId() == 0).toList();

        // 找到所有非顶级分类
        List<Category> children = list.stream().filter(c -> c.getParentId() > 0).toList();
        // 递归查找
        parents.forEach(c->{
            findChildren(c,children);
        });
        return list;
    }

    /***
     * 递归查找子分类
     */
    public void findChildren(Category category,List<Category> children){
        // 循环所有子分类,判断查找当前类的子分类
        List<Category> list = children.stream().filter(c -> Objects.equals(c.getParentId(), category.getId())).toList();
        // 如果没有子分类，则结束，有就继续查找（递归查找）
        list.forEach(c->findChildren(c,children));
        // 将查找的结果赋值给当前类的子分类属性children
        category.setChildren(list);
    }

}
